import { defineStore } from 'pinia'
import { getUserInfo } from '../api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    isLoggedIn: false
  }),
  actions: {
    async fetchUserInfo() {
      console.log('Fetching user info...')
      try {
        const res = await getUserInfo()
        if (res.code === 1 && res.data) {
          this.userInfo = res.data
          this.isLoggedIn = true
          console.log('User info fetched successfully:', res.data)
        } else {
          console.log('Failed to fetch user info:', res)
          this.userInfo = null
          this.isLoggedIn = false
        }
      } catch (error) {
        console.error('Error fetching user info:', error)
        this.userInfo = null
        this.isLoggedIn = false
      }
    },
    logout() {
      this.userInfo = null
      this.isLoggedIn = false
      console.log('User logged out. State cleared.')
    }
  }
}) 